import React from "react";
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";

class Child extends React.Component {
  state = {
    number: 111,
  };
  initChart = () => {
    // Create chart
    var chart = am4core.create("chartdiv", am4charts.XYChart);
    chart.paddingRight = 20;

    chart.data = this.generateChartData();

    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    dateAxis.baseInterval = {
      timeUnit: "minute",
      count: 1,
    };
    dateAxis.tooltipDateFormat = "HH:mm, d MMMM";

    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    valueAxis.tooltip.disabled = true;
    valueAxis.title.text = "Unique visitors";

    var series = chart.series.push(new am4charts.LineSeries());
    series.dataFields.dateX = "date";
    series.dataFields.valueY = "visits";
    series.tooltipText = "Visits: [bold]{valueY}[/]";
    series.fillOpacity = 0.3;

    chart.cursor = new am4charts.XYCursor();
    chart.cursor.lineY.opacity = 0;
    chart.scrollbarX = new am4charts.XYChartScrollbar();
    chart.scrollbarX.series.push(series);

    dateAxis.start = 0.7;
    dateAxis.end = 1;
    dateAxis.keepSelection = false;
  };
  generateChartData = () => {
    var chartData = [];
    // current date
    var firstDate = new Date();
    // now set 500 minutes back
    firstDate.setMinutes(firstDate.getDate() - 500);

    // and generate 500 data items
    var visits = 500;
    for (var i = 0; i < 500; i++) {
      var newDate = new Date(firstDate);
      // each time we add one minute
      newDate.setMinutes(newDate.getMinutes() + i);
      // some random number
      visits += Math.round(this.props.num + Math.random());
      // add data item to the array
      chartData.push({
        date: newDate,
        visits: visits,
      });
    }
    return chartData;
  };
  componentDidMount() {
    this.initChart();
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log("nextProps, nextState)", nextProps, nextState);
    return true;
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(
      "prevProps, prevState, snapshot",
      prevProps,
      prevState,
      snapshot
    );
    if (prevProps.num !== this.props.num) {
      this.initChart();
    }
  }
  render() {
    return (
      <React.Fragment>
        <div id="chartdiv" style={{ height: "500px" }}></div>
        <div>
          父级接受的 this.props
          <div>num:{this.props.num}</div>
          <div>对象：{this.props.obj.number}</div>
          <div>对象：{this.props.obj.list[0]}</div>
        </div>
      </React.Fragment>
    );
  }
}

export default Child;
